package com.loan.web.api;

import com.loan.entity.ResponseResult;
import com.loan.entity.User;
import com.loan.service.UserService;
import com.loan.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author FBF
 * 批量图片上传
 */
@RestControllerAdvice
@RequestMapping("upload")
public class UploadController {
    @Value("D://imageslocation")
    private String uploadLocation;
    @Autowired
    private UserService userService;
    @PostMapping("upload")
    public ResponseResult upload(MultipartFile[] file, HttpSession sessions) {
        //创建字符数组
        File[] files = new File[file.length];
        String name;
        String suffix = null;
        String newFileName = null;
        //遍历MultipartFile数组
        for (int i = 0; i < file.length; i++) {
            newFileName = UUIDUtil.getUUID();//自动生成文件名
            name = file[i].getOriginalFilename();//获取到传过来的图片的名字
            suffix = name.substring(name.lastIndexOf("."));//获取到传过来的文件名截取后缀
            files[i] = new File(uploadLocation + "/" + newFileName + suffix);//给传过来的图片生成路径和新的文件名
            String path = uploadLocation + "/" + newFileName + suffix;
            String username = (String) sessions.getAttribute("username");
            User user = new User();
            user.setIcon(path);
            user.setUsername(username);
            int result = userService.updateIcon(user);
            if(result == 0 ){
                return new ResponseResult(500, "上传失败请重新上传");
            }
            try {
                file[i].transferTo(files[i]);//传输图片
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        //没有异常把图片路径和信息传给前端
       return new ResponseResult(200, "上传成功",uploadLocation.concat("/").concat(newFileName).concat(suffix));

    }

}
